<template>
  <!-- 星星分数组件 -->
  <div class="star" :class="starType">
    <span
      v-for="(itemClass,index) in itemClasses"
      :class="itemClass"
      class="star-item"
      :key="index"
    ></span>
  </div>
</template>

<script>
const LENGTH = 5;
const CLS_ON = "on";
const CLS_HALF = "half";
const CLS_OFF = "off";

export default {
  props: {
    size: {
      type: Number
    },
    score: {
      type: Number //传过来的分数
    }
  },
  computed: {
    starType() {
      return "star-" + this.size;
    },
    itemClasses() {
      let result = [];
      //向下取整,拿0.5的倍数
      let score = Math.floor(this.score * 2) / 2;

      //判断有没有小数,取模不等于0肯定是有小数
      let hasDecimal = score % 1 !== 0;

      //求最接近的整数
      let integer = Math.floor(score);

      //循环整数,把整星星放进数组
      for (let i = 0; i < integer; i++) {
        result.push(CLS_ON);
      }

      //如果有小数,就是半星,那就给数组加一个半星
      if (hasDecimal) {
        result.push(CLS_HALF);
      }

      //如果数组的长度小于定于的5,说明后面有没星的,就循环添加没星的类名
      while (result.length < LENGTH) {
        result.push(CLS_OFF);
      }
      return result;
    }
  }
};
</script>

<style lang = "scss">
.star {
  font-size: 0;
  text-align: center;
  .star-item {
    display: inline-block;
    background-repeat: no-repeat;
  }
}
.star-48 {
  .star-item {
    width: 20px;
    height: 20px;
    margin-right: 22px;
    background-size: 20px 20px;
  }
}
.star-48:last-child {
  margin-right: 0;
}
.on {
  background-image: url("./star24_on@3x.png");
}
.half {
  background-image: url("./star24_half@3x.png");
}
.off {
  background-image: url("./star24_off@3x.png");
}
</style>
